package com.code2roc.xhood.asm;

import com.code2roc.xhood.model.ObscureConfig;
import com.code2roc.xhood.util.CommonUtil;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.MethodInsnNode;

import java.util.ArrayList;
import java.util.List;

public class ConstantAdapter extends MethodVisitor {
    private String packageName;
    private String key;

    public ConstantAdapter(MethodVisitor methodVisitor, ObscureConfig obscureConfig, String key) {
        super(Opcodes.ASM9, methodVisitor);
        this.packageName = obscureConfig.getPackageName();
        this.key = key;
    }

    @Override
    public void visitLdcInsn(Object cst) {
        boolean check = false;
        if (cst instanceof String && cst != null) {
            String value = String.valueOf(cst);
            if (!value.equals("") && value.length() < 1024) {
                check = true;
            }
        }
        if (check) {
            String cstStr = CommonUtil.encryptByDES(String.valueOf(cst), key);
            MethodInsnNode decryptMethodInsn = new MethodInsnNode(
                    Opcodes.INVOKESTATIC,
                    packageName.replace(".","/") + "/" + "ConstantUtil",
                    "decrypt",
                    "(Ljava/lang/String;)Ljava/lang/String;",
                    false);
            super.visitLdcInsn(cstStr);
            super.visitMethodInsn(
                    decryptMethodInsn.getOpcode(),
                    decryptMethodInsn.owner,
                    decryptMethodInsn.name,
                    decryptMethodInsn.desc,
                    decryptMethodInsn.itf);
        } else {
            super.visitLdcInsn(cst);
        }
    }
}
